﻿function openPeopleSearchFromPageWhenEnter(evt, peopleSearchFieldId, url) {
    evt = (evt) ? evt : (window.event) ? event : null;
    if (evt) {
        if (evt.keyCode == 13) {
            _searchEntered = true;
            openPeopleSearchFromPage(peopleSearchFieldId, url);
        }
    }
}


function openPeopleSearchFromPage(peopleSearchFieldId, url) {
    $("#" + peopleSearchFieldId + ":first").each(function() {
        if ($(this).val().length > 0 &&
            ($(this).attr('hasdefaulttext') == undefined ||
             $(this).attr('hasdefaulttext') == null ||
             $(this).attr('hasdefaulttext') === 'false')) {

            window.location = url + utfEncode($(this).val());
        }
    });
}

function openContextSearchFromPageWhenEnter(evt, contextFieldId, searchContext) {
    evt = (evt) ? evt : (window.event) ? event : null;
    if (evt) {
        if (evt.keyCode == 13) {
            _searchEntered = true;
            openContextSearchFromPage(contextFieldId, searchContext);
        }
    }
}

function openContextSearchFromPage(contextFieldId, searchContext) {
    var contextFieldId = document.getElementById(contextFieldId);

    if (contextFieldId && contextFieldId.checked == true) {
        $("#searchInput:first").each(function() {
            var q = $(this).val().replace(/^\s+/, "").replace(/\s{2,}/g, " ");
            if (q.length > 0 &&
                ($(this).attr('hasdefaulttext') == undefined ||
                 $(this).attr('hasdefaulttext') == null ||
                 $(this).attr('hasdefaulttext') === 'false')) {
                var urlBase = currentHost;
                if (urlBase == null || urlBase == undefined) {
                    currentHost = "";
                }
                window.location = currentHost + "/search.aspx?q=" + encodeURIComponent(q) + "&abbcontext=" + utfEncode(searchContext);
            }
        });
    }
    else {
        openSearchFromPage()
    }
}


function openSearchFromPage() {
    $("#searchInput:first").each(function () {
        var q = $(this).val().replace(/^\s+/, "").replace(/\s{2,}/g, " ");
        if (q.length > 0 &&
            ($(this).attr('hasdefaulttext') == undefined ||
             $(this).attr('hasdefaulttext') == null ||
             $(this).attr('hasdefaulttext') === 'false')) {
            window.location = "/search.aspx?q=" + encodeURIComponent(q);
        }
    });
}

function doSearchWhenEnter(evt) {
    evt = (evt) ? evt : (window.event) ? event : null;
    if (evt) {
        if (evt.keyCode == 13) {
            _searchEntered = true;
            doSearch()
        }
    }
}

function doSearch() {
    var abbpage = document.getElementById('abbpage');
    var abbcontext = document.getElementById('abbcontext');

    var parameters = '';
    if (abbcontext != undefined && abbcontext != null && abbcontext.value != "")
        parameters += '&abbcontext=' + utfEncode(abbcontext.value);
    if (abbpage != undefined && abbpage != null && abbpage.value != "" && abbpage.value != "help")
        parameters += '&abbpage=' + utfEncode(abbpage.value);

    var q = document.getElementById('searchInput');
    if (q != undefined && q != null) {
        var qval = q.value.replace(/^\s+/, "").replace(/\s{2,}/g, " ");
        if (qval != "") {
            parameters += '&q=' + encodeURIComponent(qval);
        }
    }

    if (parameters.length > 0)
        parameters = '?' + parameters.substr(1, 2000);

    var url = '/search.aspx' + parameters;
    window.location = url;
}

_searchEntered = false;
function pageFormSubmit() {
    if (_searchEntered) {
        _searchEntered = false;
        return false;
    }
    return true;
}

jQuery.fn.abbSearchPage = function(options) {
    var mother = this;

    init();
    return this;

    function init() {
        if (options.enableSuggestions) {
            initSuggestions();
        }
        initLanguageSelect();
        initFilterDropdowns();
    }

    function initFilterDropdowns() {
        var filters = mother.find(options.components.filters);
        filters.find("select").jumpMenu();
    }

    function initLanguageSelect() {
        var element = mother.find(options.components.languageSelect);
        element.abbSearchLanguageSelect();
    }

    function initSuggestions() {
        var queryField = mother.find(options.components.queryField);
        var output = mother.find(options.components.suggestions);
        queryField.abbSearchSuggestions({
            "output": output
        });
    }
}

jQuery.fn.abbSearchSuggestions = function (options) {
    var textField = this;
    var form = textField.parents("form").eq(0);
    var output = jQuery(options.output);
    var selectedIndex = -1;
    var query = "";
    var cache = {};
    var scheduledRequestTimeoutReference;
    var requestDelayMillis = 400;
    var minimumNumberOfCharacters = 1;
    var maximumNumberOfSuggestions = 5;
    var resultFormat = "full";

    init();
    return this;

    function init() {
        textField.bind("keyup", handleTypingInTextField);
        output.find("ul.autocomplete").bind("click", handleListClick);
        jQuery(document).bind("click", handleDocumentClick);
        fixIe6ZindexIssues();
    }

    function fixIe6ZindexIssues() {
        output.bgiframe();
    }

    function handleTypingInTextField(event) {
        update(event.which, event);
    }

    function handleListClick(event) {
        event.preventDefault();
        var listItem = jQuery(event.target).parents("li").eq(0);
        submitSearch(listItem.text());
    }

    function handleDocumentClick(event) {
        hideOutput();
    }

    function update(lastKey, event) {
        var isNavigationKey = handleNavigationKeys(lastKey, event);
        if (isNavigationKey) {
            return;
        }
        selectedIndex = -1;
        query = textField.val().replace(/^\s+/, "");
        if (query.length >= minimumNumberOfCharacters) {
            scheduleSuggestionsUpdate();
        } else {
            removeScheduledRequest();
            updateSuggestions([]);
            hideOutput();
        }
    }

    function scheduleSuggestionsUpdate() {
        if (scheduledRequestTimeoutReference == null) {
            scheduledRequestTimeoutReference = window.setTimeout(function () {
                scheduledRequestTimeoutReference = null;
                getSuggestions(function (suggestions) {
                    updateSuggestions(suggestions);
                });
            }, requestDelayMillis);
        }
    }

    function removeScheduledRequest() {
        if (scheduledRequestTimeoutReference != null) {
            window.clearTimeout(scheduledRequestTimeoutReference);
            scheduledRequestTimeoutReference = null;
        }
    }

    function updateSelected() {
        var items = output.find("li");
        items.removeClass("selected");
        selectedIndex = Math.min(items.size() - 1, selectedIndex);
        if (selectedIndex >= 0) {
            var suggestion = items.eq(selectedIndex);
            suggestion.addClass("selected");
            textField.val(suggestion.text());
        } else {
            textField.val(query);
        }
    }

    function updateSuggestions(suggested) {

        if (typeof (suggested.SearchSuggestions) == "undefined") {
            populateSuggestionList("");
            populatePromotedList("");
        } else {
            populateSuggestionList(suggested.SearchSuggestions.Suggestions);
            //populatePromotedList(suggested.PromotedPages); removed from 20091212 release.
            if (suggested.SearchSuggestions.Suggestions.length > 0) {
                showOutput();
            }
            else {
                hideOutput();
            }
        }
    }

    function populatePromotedList(promoted) {
        var promotedList = output.find("ul.promoted");
        var maxNumberOfEntriesToShow = 3;
        promotedList.empty();
        if (promoted.length > 0) {
            for (var i = 0; i < promoted.length; i++) {
                promotedList.append(formatPromotedListItem(promoted[i]));
                if (i >= (maxNumberOfEntriesToShow - 1)) { break; }
            }
        }
    }

    function populateSuggestionList(suggestions) {
        var list = output.find("ul.autocomplete");
        list.empty();
        if (suggestions.length > 0) {
            list.empty();
            for (var i = 0; i < suggestions.length; i++) {
                list.append(formatSuggestionListItem(query, suggestions[i]));
            }
        }
    }

    function formatSuggestionListItem(query, suggestion) {
        var emphasized = suggestion.replace(new RegExp(query, "i"), "<em>$&</em>");
        var listItem = '<li><a href="#">{0}</a></li>'.replace("{0}", emphasized);
        return listItem;
    }

    function formatPromotedListItem(promoted) {
        var listItem = '<li><a href="{0}"><strong class="title">{1}</strong><span class="body">{2}</span></a></li>'.replace("{0}", promoted.LinkUri).replace("{1}", promoted.Heading).replace("{2}", promoted.BodyText);
        return listItem;
    }

    function getSuggestions(callback) {
        query = textField.val().replace(/^\s+/, "").replace(/\s{2,}/g, " "); // trim leading whitespace, and replace all multiple whitespace to one
        if (query.length == 0) return;

        var results = getCachedSuggestions(query);
        if (results != null) {
            callback(results);
        } else {
            loadSuggestionsFromServer(query, function (results) {
                addCachedSuggestions(query, results);
                callback(results);
            });
        }
    }

    function loadSuggestionsFromServer(query, callback) {
        jQuery.ajax({
            dataType: "json",
            url: "/search/services/suggest.aspx",
            data: {
                token: query,
                maxmatches: maximumNumberOfSuggestions + 1,
                resultformat: resultFormat
            },
            success: function (results) {
                removeFirstOrLast(results.SearchSuggestions.Suggestions, query);
                callback(results);
            },
            error: function () {
                callback([]);
            }
        });
    }

    function getCachedSuggestions(query) {
        return cache[query];
    }

    function addCachedSuggestions(query, results) {
        cache[query] = results;
    }

    function removeFirstOrLast(suggestions, query) {
        if (suggestions.length > 0 && suggestions[0].toLowerCase() == query.toLowerCase()) {
            suggestions.shift();
        } else if (suggestions.length > maximumNumberOfSuggestions) {
            suggestions.pop();
        }
    }

    function revertAndClose() {
        hideOutput();
        textField.val(query);
    }

    function submitSearch(text) {
        textField.val(text);
        if (options.handleSearch != null) {
            options.handleSearch(text);
        } else {
            doSearch();
        }
    }

    function showOutput(callback) {
        if (output.is(":not(.open)")) {
            output.find("ul.promoted").show();
            if (output.find("ul.promoted").html() == "") {
                output.find("ul.promoted").hide();
            }
            textField.trigger("suggestionsOpened");
            output
                .slideDown(1, function () {
                    output.addClass("open");
                    if (callback != null) { callback(); }
                }
            );
        }
    }

    function hideOutput(callback) {
        textField.trigger("suggestionsClosed");
        output.removeClass("open").hide();
        if (callback != null) { callback(); }
    }

    function handleNavigationKeys(key, event) {
        var handled = false;
        if (key == 27) {        // escape
            handled = true;
            revertAndClose();
        } else if (key == 13) { // enter
            handled = true;
        } else if (key == 38) { // arrow up
            selectedIndex = Math.max(-1, selectedIndex - 1);
            updateSelected();
            handled = true;
        } else if (key == 40) { // arrow down
            selectedIndex++;
            updateSelected();
            handled = true;
        }
        return handled;
    }
}

jQuery.fn.abbSearchLanguageSelect = function() {
    var mother = this;

    var preferences = mother.find(".preferences");
    var change = mother.find("a.change");
    var cancel = preferences.find("a.cancel");
    var chooseTitle = mother.find(".languages .choose");
    var currentTitle = mother.find(".languages .current");

    init();
    return this;

    function init() {
        initShowHide();
        initAllOrSpecific();
    }

    function initAllOrSpecific() {
        preferences.find(".allOrSpecific input").bind("click", updateAllOrSpecific);
        updateAllOrSpecific();
    }

    function updateAllOrSpecific() {
        var all = preferences.find(".allOrSpecific input").eq(0);
        var specific = preferences.find(".allOrSpecific input").eq(1);
        var checkboxes = preferences.find(".specify input[type=checkbox]");
        if (all.is(":checked")) {
            checkboxes
                .prop("disabled", "disabled")
                .prop("checked", "");
            preferences.find(".specify label").css("opacity", .3);
        } else if (specific.is(":checked")) {
            checkboxes.prop("disabled", "");
            preferences.find(".specify label").css("opacity", 1);
        }
    }

    function initShowHide() {
        change.show();
        chooseTitle.hide();
        currentTitle.show();
        preferences.hide();
        change.bind("click", function(event) {
            event.preventDefault();
            preferences.slideDown();
            currentTitle.hide();
            chooseTitle.fadeIn();
        });
        cancel.bind("click", function(event) {
            event.preventDefault();
            preferences.slideUp("fast");
            chooseTitle.hide();
            currentTitle.fadeIn();
        });
    }
}

jQuery.fn.abbSearchResultIndicator = function(options) {
    var mother = this;

    init();
    return this;

    function init() {
        updateMissingResultItems();
    }

    function updateMissingResultItems() {
        var missingResultItems = mother.find("li:not(.selected)");
        missingResultItems.addClass("loading");
        updateItemsWithDelay(missingResultItems);
    }

    function updateItemsWithDelay(items) {
        var itemNumber = 0;
        jQuery.timer(options.delay, function(timer) {
            update(items[itemNumber]);

            itemNumber = itemNumber + 1;
            if (itemNumber == items.length) {
                timer.stop();
            }
        });
    }

    function update(item) {
        var missingResultItem = jQuery(item);
        var query = extractQueryFrom(missingResultItem);
        query = addCacheBuster(query);

        callService(query, updateResultNumber);

        function updateResultNumber(data) {
            missingResultItem.removeClass("loading");
            var formattedData = "(" + data + ")";
            missingResultItem.find(".numOfResults").text(formattedData);
        }
    }

    function extractQueryFrom(item) {
        var url = item.find("a").attr("href");
        return url.split("?")[1];
    }

    function addCacheBuster(query) {
        var timestamp = "&timestamp=" + (new Date()).getTime();
        return query + timestamp;
    }

    function callService(query, onSuccessCallback) {
        jQuery.ajax({
            url: options.serviceUrl,
            type: "GET",
            data: query,
            dataType: "json",
            success: onSuccessCallback
        });
    }
}
